import {BASE_URL} from '@/api/config.js'
class Uploader {
	constructor() {
	}
	
	upload(file,options={}){
		return new Promise((resolve, reject)=>{
			const Authorization =uni.getStorageSync('token')
			let reqData = {
				baseUrl: BASE_URL,
				actionUrl: '/api/common/upload',
				fileName: 'file'
			}
			reqData = Object.assign({}, reqData, options)
			uni.uploadFile({
				url: reqData.baseUrl + reqData.actionUrl,
				filePath: file,
				name: reqData.fileName,
				header: {
					"Token": Authorization
				},
				success: uploadFileRes => {
					const result = typeof uploadFileRes.data === 'string' ?
						JSON.parse(uploadFileRes.data) : uploadFileRes.data
						console.log(result)
					if (result.code !== 1) {
						uni.showToast({
							title: result.message,
							icon: 'none',
							position: 'bottom'
						})
					}
					resolve(result)
				},
				fail: failRes => {
					uni.showToast({
						title: '上传图片失败',
						icon: 'none',
						position: 'bottom'
					})
					reject(failRes)
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		})
	}

	choiceUpload(options = {}) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				success: async chooseImageRes => {
					const tempFilePaths = chooseImageRes.tempFilePaths
					uni.showLoading({
						title: '上传中...'
					})
					this.upload(tempFilePaths[0],options).then(res=>{
						resolve(res)
					}).catch(err=>{
						reject(err)
					})
				}
			})
		})
	}



}

export default Uploader
